from django.core.mail import send_mail  # 邮箱需要
from django.conf import settings
from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *
from django.contrib.auth.hashers import make_password, check_password  # 加密和解密方法
import re  # 正则
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired

serializer = Serializer(settings.SECRET_KEY, 100)  # 加密时间限制

user_token = Serializer(settings.SECRET_KEY)


class CateView(APIView):  # 分类的增删改查
    def post(self, request):
        if CateModel.objects.filter(cate_name=request.data.get('cate_name')):
            return Response({'msg': '该分类已存在', 'code': 400})
        ser = CateSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '添加失败', 'code': 400})

    def get(self, request):
        cate_obj = CateModel.objects.all()
        ser = CateSer(cate_obj, many=True)
        return Response(ser.data)

    def put(self, request, cate_id):
        cate_obj = CateModel.objects.filter(pk=cate_id).first()

        if cate_obj:
            cate_obj.cate_name = request.data.get('cate_name')
            cate_obj.cate_img = request.data.get('cate_img')
            return Response({'msg': '修改成功', 'code': 200})
        else:
            return Response({'msg': '该分类不存在', 'code': 400})

    def delete(self, request, cate_id):
        cate_obj = CateModel.objects.filter(pk=cate_id)
        if cate_obj:
            cate_obj.delete()
            return Response({'msg': '删除成功', 'code': 200})
        else:
            return Response({'msg': '该分类不存在', 'code': 400})


class PictureView(APIView):
    def get(self, request):
        # 获取所有的图片
        picture_obj = PictureModel.objects.all()
        ser = PictureSer(picture_obj, many=True)
        return Response(ser.data)


class GoodsView(APIView):  # 商品的添加展示
    def post(self, request):
        if GoodsModel.objects.filter(goods_name=request.data.get('goods_name')):
            return Response({'msg': '该商品已存在', 'code': 400})
        ser = GoodsSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            print(ser.errors)
            return Response({'msg': '添加失败', 'code': 400})

    def get(self, request):
        goods_obj = GoodsModel.objects.all()
        ser = GoodsSer(goods_obj, many=True)
        return Response(ser.data)


class RegisterView(APIView):  # 注册接口
    """
    {'username': ['wangxiaochen'], 'password1': ['123'], 'pass
word2': ['123'], 'email': ['642320700@qq.com']}
    """

    def post(self, request):
        print(request.data)
        username = request.data.get('username')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        email = request.data.get('email')
        if not re.match(r'[0-9a-zA_]{0,19}@(.*?).com', email):  # 判断邮箱
            return Response({'msg': '邮箱不符合规则', 'code': 400})
        user_obj = UserModel.objects.filter(username=username).first()
        if user_obj:  # 判断用户存不存在
            return Response({'msg': '用户已存在', 'code': 400})
        if password1 == password2:
            data = {
                'username': username,
                'password': make_password(password1),
                'email': email
            }
            ser = UserSer(data=data)
            if ser.is_valid():
                ser.save()
                # 数据保存以后可以发邮件
                user_obj = ser.data
                user_info = {'user_id': user_obj.get('id')}  # 把用户信息制作成字典
                token = serializer.dumps(user_info).decode()  # 对用户信息进行加密
                subject = '好友多会员注册'  # 主题
                message = '欢迎注册好又多'  # 消息
                from_email = settings.EMAIL_FROM  # 需要导入settings
                recipient_list = [email]
                html_message = '<h3>欢迎注册好又多会员，请点击一以下链接进行激活：</br><a href="http://127.0.0.1:8000/app01/register/?token={}">激活会员点击这里</a></h3>'.format(
                    token)
                send_mail(subject=subject,
                          message=message,
                          from_email=from_email,
                          recipient_list=recipient_list,
                          html_message=html_message)
                return Response({'msg': '注册成功', 'code': 200})
            else:
                print(ser.errors)
                return Response({'msg': '注册失败', 'code': 400})
        else:
            return Response({'msg': '两次密码不一致', 'code': 400})

    def get(self, request):
        print(request.data.get('token'))
        token = request.GET.get('token')
        try:
            user_info = serializer.loads(token)
            print(user_info)
            return Response({'msg': 'ok', 'code': 200, 'token': user_info})
        except SignatureExpired:
            return Response({'msg': '激活失败', 'code': 400})


class AddMarkdownView(APIView):
    def post(self, request):
        print(request.data)
        return Response({'msg': 'ok', 'code': 200})


class LoginView(APIView):
    def post(self, request):
        print(request.data)
        username=request.data.get('username')
        password=request.data.get('password')
        user_obj=UserModel.objects.filter(username=username).first()
        if user_obj:
            if check_password(password,user_obj.password):
                user_info={'user_id':user_obj.pk}
                token=user_token.dumps(user_info).decode()
                # 把生成的token值存起来
                UserTokenModel.objects.update_or_create(user=user_obj,defaults={'token':token})
                return Response({'msg': '登录成功', 'code': 200,'token':token})
            else:
                return Response({'msg': '用户或密码错误', 'code': 400})
        else:
            return Response({'msg': '用户或密码错误', 'code': 400})
